package com.quartz.config;

import com.quartz.job.HouseKeepJob;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;

import java.util.Map;
import java.util.TimeZone;

/**
 * 从配置文件读取配置并持久化到数据库
 */
@Configuration
@ConfigurationProperties(prefix = "quartz")
public class QuartzJobConfig {
    private Map<String, JobConfig> jobConfig;

    public Map<String, JobConfig> getJobConfig() {
        return jobConfig;
    }

    public void setJobConfig(Map<String, JobConfig> jobConfig) {
        this.jobConfig = jobConfig;
    }

    public static class JobConfig {
        private String triggerCronExpression;
        private String triggerTimeZone;

        public String getTriggerCronExpression() {
            return triggerCronExpression;
        }

        public void setTriggerCronExpression(String triggerCronExpression) {
            this.triggerCronExpression = triggerCronExpression;
        }

        public String getTriggerTimeZone() {
            return triggerTimeZone;
        }

        public void setTriggerTimeZone(String triggerTimeZone) {
            this.triggerTimeZone = triggerTimeZone;
        }

    }

    @Bean
    public JobDetailFactoryBean houseKeepJobDetailFactory(){
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(HouseKeepJob.class);
        factoryBean.setDurability(true);
        factoryBean.setName("houseKeepJob");
        return factoryBean;
    }

    @Bean
    public JobDetail houseKeepJobDetail(){
        return houseKeepJobDetailFactory().getObject();
    }

    @Bean
    public Job houseKeepJob(){
        HouseKeepJob job = new HouseKeepJob();
        return job;
    }

    @Bean
    public CronTriggerFactoryBean houseKeepJobTriggerFactory(){
        CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
        factoryBean.setJobDetail(houseKeepJobDetail());
        factoryBean.setCronExpression(this.jobConfig.get("houseKeepJob").getTriggerCronExpression());
        factoryBean.setTimeZone(TimeZone.getTimeZone(this.jobConfig.get("houseKeepJob").getTriggerTimeZone()));
        factoryBean.setName("houseKeepJobTrigger");
        return factoryBean;
    }

    @Bean
    @ConditionalOnBean(name = "houseKeepJobTriggerFactory")
    public Trigger houseKeepJobTrigger(){
        CronTrigger trigger = houseKeepJobTriggerFactory().getObject();
        return trigger;
    }

}
